﻿window.ProductDetail = Backbone.Model.extend({
    urlRoot: 'api/product/',
    url: function () {
        return this.urlRoot + localStorage.getItem('productid');
    },
    defaults: {
        BaskOrderLogCount: 0
    },
    parse: function (model) {
        model['BaskOrderLogCount'] = model['BaskOrderLogCount'] || this.defaults.BaskOrderLogCount;
        for (i in model['Images']) {
            model['Images'][i] = { src: model['Images'][i] };
        };
        model['hasImages'] = model['Images'].length > 0;
        return model;
    }
});

window.Comment = Backbone.Model.extend({});

window.CommentList = Backbone.Collection.extend({
    model: Comment,
    urlRoot: 'api/product/comment/',
    url: function () {
        return this.urlRoot + localStorage.getItem('productid');
    }
});

window.OrderComment = Backbone.Model.extend({});

window.OrderCommentDetail = Backbone.Model.extend({
    urlRoot: 'api/product/baskorderlogdetail/',
    url: function () {
        return this.urlRoot + localStorage.getItem('ordercommentid');
    }
});

window.OrderCommentList = Backbone.Collection.extend({
    model: OrderComment,
    urlRoot: 'api/product/baskorderlog/',
    url: function () {
        return this.urlRoot + localStorage.getItem('productid');
    }
});

window.ProductDetailView = Backbone.View.extend({
    el: '#jqt',
    initialize: function () {
        this.template = $('#ProductDetailTemplate').html();
        this.model = new ProductDetail();
        this.commentList = new CommentList();
        this.orderCommentList = new OrderCommentList();
        this.orderCommentDetail = new OrderCommentDetail();
    },

    events: {
        'click #ProductDetail .sliding li': 'fetchSpecific',
        'click #ProductDetail .p_intro_info .ul-detail,.p_summary .arrow-prdetail': 'fetchDetail',
        'click #ProductDetail .p_intro_info .ul-comment': 'fetchComment',
        'click #ProductDetail .p_intro_info .ul-orderComment': 'fetchOrderComment',
        'click #ProductDetail #p_ordercomment li': 'fetchOrderCommentDetail',
        'click #add_cart': 'addToMyCart',
        'click #addFavorite': 'addToMyCollect'
    },

    render: function () {
        var partial = { header: $('#HeaderTemplate').html(), footer: $('#FooterTemplate').html(),
            innerFooter: $('#InnerFooterTemplate').html(), sliding: $('#SlideTitleTemplate').html(),
            pictureList: $('#PictureSlideTemplate').html()
        };
        var data = { hasBack: true, title: "返回", btnListR: [{ name: 'sort' }, { name: 'cart' }, { name: 'home'}] };

        this.$el.append(Mustache.render(this.template, data, partial));

        this.setFetchType();

        this.fetchSpecific();

        return this;
    },

    fetchSpecific: function (e) {
        if (e) {
            var target = $(e.currentTarget);
            localStorage.setItem('detailType', target.attr('detail'));
            this.setFetchType();
        }
        var type = localStorage.getItem('detailType');
        switch (type) {
            case 'tab_intro': this.fetchIntro(); break;
            case 'tab_detail': this.fetchDetail(); break;
            case 'tab_comment': this.fetchComment(); break;
            case 'tab_orderComment': this.fetchOrderComment(); break;
            default: this.fetchIntro(); break;
        }
    },

    fetchIntro: function () {
        var that = this,
            type = 'tab_intro';
        localStorage.setItem('detailType', type); this.setFetchType();
        $('#p_intro').show().siblings().hide();
        this.model.fetch({
            success: function () {
                var template = $('#IntroContentTemplate').html();
                var partial = { pictureSlide: $('#PictureSlideTemplate').html(), productSummary: $('#SummaryTemplate').html(),
                    commentSample: $('#SampleCommentTemplate').html()
                }
                
                $('#p_intro').html(Mustache.render(template, that.model.toJSON(), partial));
                $('.flexslider').flexslider({
                    animation: "slide",
                    slideshow: false
                });

                if (that.model.get('RepertoryCount') == 0) {
                    $('#add_cart').hide();
                }

                pageView.resizeScroll();

                $('li#Specifications').html(Mustache.render($('#DetailContentTemplate').html(),
                { props: that.model.get('ProductProperty') || {} }, []));
                $('#p_detail').html(Mustache.render($('#DetailContentTemplate').html(), that.model.toJSON(), []));
            }
        });
    },

    fetchDetail: function () {
        var that = this,
            type = 'tab_detail';
        localStorage.setItem('detailType', type); this.setFetchType();
        $('#p_detail').show().siblings().hide();

        this.model.fetch({
            success: function () {
                var template = $('#DetailContentTemplate').html();
                var propTemplate = $('#SpecificationsTemplate').html(),
                    propData = { props: that.model.get('ProductProperty') || {} }
                $('li#Specifications').html(Mustache.render(propTemplate, propData, []));
                $('#p_detail').html(Mustache.render(template, that.model.toJSON(), []));
                pageView.resizeScroll();

                $('#p_intro').html(Mustache.render($('#IntroContentTemplate').html(), that.model.toJSON(),
                    { pictureSlide: $('#PictureSlideTemplate').html(), productSummary: $('#SummaryTemplate').html(),
                        commentSample: $('#SampleCommentTemplate').html()
                    }));
            }
        });



    },

    fetchComment: function () {
        var that = this,
            type = 'tab_comment';
        localStorage.setItem('detailType', type); this.setFetchType();
        $("#p_comment").show().siblings().hide();
        this.commentList.fetch({
            data: {
                startPage: +localStorage.getItem('commentPageIndex'),
                pageSize: 5
            },
            success: function () {
                var commentList = that.commentList.models[0].get('Data'),
                    allCount = that.commentList.models[0].get('Count');
                if (allCount == 0) {
                    var template = $('#EmptyCommentContentTemplate').html();
                    $('#p_comment').html(Mustache.render(template, [], []));
                    $('.footer').hide();
                    return;
                }
                var template = $('#CommentContentTemplate').html();
                var data = { commentList: commentList };
                var partial = { commentSample: $('#DetailCommentTemplate').html() };
                $('#p_comment').html(Mustache.render(template, data, partial));
                new Plugins.PagingPlugin('.foot-paging', {
                    allCount: allCount,
                    pageIndexKey: 'commentPageIndex',
                    prevCall: function (e) { that.fetchPrevComment(e); },
                    nextCall: function (e) { that.fetchNextComment(e) },
                    numberClickCall: function (e) { that.fetchSpecificComment(e) }
                });
                pageView.resizeScroll();
            }
        });
    },

    fetchPrevComment: function (e) {
        if ($(e.currentTarget).hasClass('disable')) return;
        var pageIndex = localStorage.getItem('commentPageIndex');
        localStorage.setItem('commentPageIndex', +pageIndex - 1);
        this.fetchComment();
    },

    fetchNextComment: function (e) {
        if ($(e.currentTarget).hasClass('disable')) return;
        var pageIndex = localStorage.getItem('commentPageIndex');
        localStorage.setItem('commentPageIndex', +pageIndex + 1);
        this.fetchComment();
    },

    fetchSpecificComment: function (e) {
        var target = $(e.currentTarget);
        if (target.hasClass('gray')) return;
        var index = +target.attr('index');
        localStorage.setItem('commentPageIndex', index);
        this.fetchComment();
    },

    fetchOrderComment: function () {
        var that = this,
            type = 'tab_orderComment';
        localStorage.setItem('detailType', type); this.setFetchType();
        $('#p_ordercomment').show().siblings().hide();

        this.orderCommentList.fetch({
            data: {
                startPage: +localStorage.getItem('ordercommentPageIndex'),
                pageSize: 5
            },
            success: function () {
                var orderComments = that.orderCommentList.models[0].get('Data'),
                    allCount = that.orderCommentList.models[0].get('Count');
                if (allCount == 0) {
                    var template = $('#EmptyOrderCommentContentTemplate').html();
                    $('#p_ordercomment').html(Mustache.render(template, [], []));
                    $('.footer').hide();
                    return;
                }
                var template = $('#OrderCommentContentTemplate').html();
                var data = { orderComments: orderComments };
                $('#p_ordercomment').html(Mustache.render(template, data, []));
                new Plugins.PagingPlugin('.foot-paging', {
                    allCount: allCount,
                    pageIndexKey: 'ordercommentPageIndex',
                    prevCall: function (e) { that.fetchPrevOrderComment(e); },
                    nextCall: function (e) { that.fetchNextOrderComment(e) },
                    numberClickCall: function (e) { that.fetchSpecificOrderComment(e) }
                });
                pageView.resizeScroll();
            }
        });
    },

    fetchPrevOrderComment: function (e) {
        if ($(e.currentTarget).hasClass('disable')) return;
        var pageIndex = localStorage.getItem('ordercommentPageIndex');
        localStorage.setItem('ordercommentPageIndex', +pageIndex - 1);
        this.fetchOrderComment();
    },

    fetchNextOrderComment: function (e) {
        if ($(e.currentTarget).hasClass('disable')) return;
        var pageIndex = localStorage.getItem('ordercommentPageIndex');
        localStorage.setItem('ordercommentPageIndex', +pageIndex + 1);
        this.fetchOrderComment();
    },

    fetchSpecificOrderComment: function (e) {
        var target = $(e.currentTarget);
        if (target.hasClass('gray')) return;
        var index = +target.attr('index');
        localStorage.setItem('ordercommentPageIndex', index);
        this.fetchOrderComment();
    },

    fetchOrderCommentDetail: function (e) {
        var target = $(e.currentTarget),
            that = this;
        localStorage.setItem('ordercommentid', target.attr('orderid'));

        this.orderCommentDetail.fetch({
            success: function () {
                var template = $('#OrderCommentDetailTemplate').html();
                var data = { orderDetail: that.orderCommentDetail.get('BaskOrderLog'), comments: that.orderCommentDetail.get('BaskOrderComments') };
                var partial = { detail: $('#OrderCommentContentDetailTemplate').html(),
                    commentList: $('#OrderCommentListDetailTemplate').html(),
                    pictureSlide: $('#PictureSlideTemplate').html()
                };
                $('#p_ordercomment').html(Mustache.render(template, data, partial));
                $('.flexslider').flexslider({
                    animation: "slide",
                    slideshow: false
                });
                pageView.resizeScroll();
            }
        });

    },

    setFetchType: function () {
        var type = localStorage.getItem('detailType'),
            activeClass = 'selected',
            target = $('#ProductDetail .sliding').find('li[detail="' + type + '"]');
        $(target).addClass(activeClass).siblings().removeClass(activeClass);

        pageView.resizeScroll();
    },

    addToMyCart: function () {
        if (pageView.getCookieValue('uid')) {
            var product = JSON.parse(localStorage.getItem('productDetail'));
            MyCartView.addToCarts(product['productid'], product['price'], 1, function () {
                pageView.goTo('MyCart');
            });
        } else {
            localStorage.setItem('loginfrom', 'addCart');
            pageView.goTo('Login');
        }
    },

    addToMyCollect: function () {
        if (pageView.getCookieValue('uid')) {
            MyCollectView.addToMyCollect(function () {
                pageView.goTo('MyCollect');
            });
        } else {
            localStorage.setItem('loginfrom', 'addCollect');
            pageView.goTo('Login');
        }
    }
});